package chen;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class dgutLogin{
    public dgutLogin(){

    }

    public static void loginDGUT(User1 userDTO, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //读取文件中的内容
        int flag = 1;
        FileInputStream file = null;
        BufferedReader in = null;

        try {
            file = new FileInputStream("src/main/User.txt");
            in = new BufferedReader(new InputStreamReader(file));

        } catch (FileNotFoundException e) {
            response.sendRedirect("/error.html");
        }
        String usermessage = null;
        StringBuffer buf = new StringBuffer();
        Jsonb jsonb = JsonbBuilder.create();
        while ((usermessage = in.readLine()) != null)
        {
            User2 messageDTO = jsonb.fromJson(usermessage, User2.class);
            if(messageDTO.getSno().equals(userDTO.getUsername()))
            {
                flag = 0;
                HttpSession session = request.getSession(true);
                Map<String,String> hashmap = new HashMap<String,String>();
                hashmap.put("username",messageDTO.getUsername());
                hashmap.put("password",messageDTO.getPassword());
                hashmap.put("email",messageDTO.getEmail());
                hashmap.put("sno",messageDTO.getSno());
                hashmap.put("img",messageDTO.getImg());
                hashmap.put("name",messageDTO.getName());
                //HttpSession session = request.getSession(true);
                session.setAttribute("usermessage", hashmap);
                session.setAttribute("token", "not null");
                String str2 = hashmap.toString();
                System.out.println(str2);
            }
            buf.append(usermessage + '\n');
        }
        BufferedWriter out = null;
        if(flag == 1)
        {
            User2 messageDTO = new User2(userDTO.getUsername()," ","123456",userDTO.getUsername(),"boy.jpg",userDTO.getName());
            String str = jsonb.toJson(messageDTO);
            buf.append(str + '\n');
        }
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/main/User.txt")));

        } catch (Exception e) {
            response.sendRedirect("/error.html");
        }

        out.write(buf.toString());
        out.close();
        response.sendRedirect("/index.jsp");
    }





}
